package com.demo.entity;

import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义类加载器
 * 注: 如果没有指定父加载器, 那么默认就是以AppClassLoader作为父加载器
 *
 * @author huangChao
 **/
public class CustomClassLoader extends ClassLoader {
    private Class<?> emptyClass;

    @Override
    public Class<?> loadClass(String className) throws ClassNotFoundException {
        if (className.equalsIgnoreCase("com.demo.entity.Empty")
                && emptyClass == null
        ) {
            // 向上进行查找class是否加载
            emptyClass = findClass(className);
            return emptyClass;
        }
        return super.loadClass(className);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        String classPath = name.replace(".", "/") + ".class";
        InputStream classInputStream = getSystemClassLoader().getResourceAsStream(classPath);
        try {
            byte[] classBytes = new byte[classInputStream.available()];
            classInputStream.read(classBytes);
            Class clazz = defineClass(name, classBytes, 0, classBytes.length);
            resolveClass(clazz);
            return clazz;
        } catch (IOException e) {
            throw new ClassNotFoundException();
        }

    }
}
